<template>
    <div class="search-detail-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">加载中...</div>
        <!-- 搜索结果列表 -->
        <div class="search-item" v-for="(item, index) in searchContent" :key="index">
            <!-- 用户信息区域 -->
            <div class="user-info">
                <el-avatar :src="item.userInfo.avatar" class="user-avatar"></el-avatar>
                <div class="user-meta">
                    <span class="username">{{ item.userInfo.username }}</span>
                    <span class="post-time">{{ item.createTime }}发布</span>
                </div>
            </div>

            <!-- 内容主体 -->
            <div class="content-box">
                <div class="content-text" v-html="filterContent(item.content)"></div>
                <div class="content-img">
                    <el-image v-for="(url, idx) in item.imageUrls" :key="idx" :src="url" fit="cover"
                        class="content-image">
                    </el-image>
                </div>
            </div>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="!loading && !searchContent.length" description="暂无搜索结果"></el-empty>

        <!-- 在列表底部添加加载触发器 -->
        <LoadMoreTrigger v-if="searchContent.length > 0" :loading="loading" :hasMore="hasMore"
            @load-more="getSearchList" />
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import service from '@/utils/request';

// 新增组件导入
import LoadMoreTrigger from '@/components/LoadMoreTrigger.vue';

const route = useRoute();
const searchContent = ref([]);
const loading = ref(true); // 新增加载状态
const page = ref(1);
const pageSize = ref(10);

const hasMore = ref(true)

const getSearchList = async () => {
    try {
        loading.value = true;
        const res = await service.get('/search/results', {
            params: {
                keyword: route.query.q,
                page: page.value,
                pageSize: pageSize.value
            }
        });
        if (res.code === 200) {
            // 追加新数据并翻页
            searchContent.value = [...searchContent.value, ...res.data.records];
            page.value++;
            // 判断是否还有更多数据
            hasMore.value = res.data.records.length >= pageSize.value;
        }
    } catch (error) {
        hasMore.value = false;
    } finally {
        loading.value = false;
    }
};

// 初始化时直接加载第一页
onMounted(() => {
    getSearchList();
});

// 在script setup部分新增过滤方法
const filterContent = (html) => {
    return html
        .replace(/<img[^>]*>/g, '') // 移除图片标签
        .replace(/<p><br><\/p>/g, ''); // 新增移除空段落
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/SearchDetail.scss';
</style>